package com.pyg.shop.service;

import com.pyg.pojo.TbSeller;
import com.pyg.sellergoods.service.SellerService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 自定义的认证类
 * @author: hb
 * @Date: 2019-05-13 14:47
 */
public class UserDetailsServiceImpl  implements UserDetailsService {
    //该实例对象是由pyg-sellergoods-service服务器提供(dobbox管理)
    private SellerService sellerService; //提供setter方法,使用配置文件进行注入

    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }
    /**
     * @Description:  如果认证成功,那么返回UserDetails权限,如果不成功返回null
     **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("++++++++userDetailsService#loadUserByUsername++++++++");
        //对用户权限的描述
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //指定一个权限
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_SELLER"));
        TbSeller seller = sellerService.findOne(username);
        if(seller!=null){
            //如果商家没有审核通过或者被关闭,不允许登录
            if(!"1".equals(seller.getStatus())){
                return null;
            }

            return new User(username,seller.getPassword(),grantedAuthorities);
        }else{
            return null;
        }

    }
}
